package com.mediacloud.app.newsmodule.fragment.baoliao.api;

import android.text.TextUtils;
import android.util.Log;

import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.util.HTTPClient;
import com.mediacloud.app.user.net.JSONObjectConvertFactory;
import com.mediacloud.app.user.net.SSLSocketClient;
import com.mediacloud.app.user.net.SignInterceptor;
import com.mediaclound.appfactnet.utils.GETBadInterceptor;
import com.mediacloud.app.util.ProxyUtil;

import org.json.JSONObject;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.X509TrustManager;

import io.reactivex.Observable;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;

/**
 * @author Heaven Created on 2022/3/14
 * spidermember
 */
public class MemberApi {
    private volatile static MemberApi.IMemberApi memberApi;

    public static MemberApi.IMemberApi getMemberApi() {
        if (memberApi == null) {
            synchronized (MemberApi.class) {
                if (memberApi == null) {
                    initMemberApi();
                }
            }
        }
        return memberApi;
    }

    private static void initMemberApi() {
        String baseUrl = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.member;
        //String baseUrl = "https://console.demo.chinamcloud.cn/memberapi";
        if (TextUtils.isEmpty(baseUrl)) {
            Log.e("DataInvokeUtil", "initMemberApi failed spider_cms is null");
            return;
        }
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.dns(new MyDns());
        ProxyUtil.config(builder);
        builder.protocols(Collections.unmodifiableList(Arrays.asList(Protocol.HTTP_1_1, Protocol.HTTP_2)));
        builder.addInterceptor(new SignInterceptor());
        builder.addInterceptor(new GETBadInterceptor(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.member,AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.cdn_member));
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(loggingInterceptor);
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), (X509TrustManager) SSLSocketClient.getTrustManager()[0]);
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        builder.readTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        builder.connectTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl + "/")
                .addConverterFactory(new JSONObjectConvertFactory())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
        memberApi = retrofit.create(IMemberApi.class);
    }

    public interface IMemberApi {
        /**
         * 记录用户日志行为
         * */
        @POST("api/action-log")
        Observable<JSONObject> actionLog(@Body RequestBody body);

        @POST("api/clockin/sign")
        Observable<JSONObject> clockIn(@Body RequestBody body);

        @POST("api/clockin/mission/findList")
        Observable<JSONObject> clockList(@Body RequestBody body);

        @POST("api/clockin/log/rankList")
        Observable<JSONObject> rankList(@Body RequestBody body);

        @GET("api/member/handlePrivacy")
        Observable<JSONObject> handlePrivacy(@Query("userId") String userId,@Query("tenantid") String tenantid);

        @GET("api/medal/page-member")
        Observable<JSONObject> getUserMember(@Query("pageNumber") int pageNumber,@Query("pageSize") int pageSize, @Query("memberId") String memberId,@Query("medalType") String medalType,
                                             @Query("memberAwarded") String memberAwarded);
        @GET("api/medal/page-member")
        Observable<JSONObject> getPageMember(@Query("pageNumber") int pageNumber,@Query("pageSize") int pageSize
                , @Query("memberId") String memberId
                ,@Query("medalType") String medalType);

        /**
         *佩戴勋章
         */
        @POST("api/medal/wear")
        @FormUrlEncoded
        Observable<JSONObject> medalWear(@Field("memberId") String memberId,@Field("medalId") String medalId
                ,@Field("wear") String wear);
        //Observable<JSONObject> medalWear(@Body RequestBody body);
        /**
         *获取已达到的等级信息（等级图标，等级达到时间）
         */
        @GET("api/rankLevelLog/getAllRankLevelInfo")
        Observable<JSONObject> getAllRankLevelInfo(
                @Query("tenantid") String tenantid, @Query("memberId") String memberId);
        /**
         *查询勋章墙
         */
        @GET("api/medal/member-medal-wall")
        Observable<JSONObject> getMedalWall(
                @Query("tenantid") String tenantid, @Query("memberId") String memberId, @Query("medalType") String medalType);

        /**
         *获取账号等级信息接口
         * @return
         */
        @GET("api/rankLevel/getMemberRankLevel")
        Observable<JSONObject> sendMemberRankLevelRequest( @Query("memberId") String memberId);

        /**
         *代理商重定向地址
         * @return
         */
        @GET("api/integralMall/loginRedirectUrl")
        Observable<JSONObject> loginRedirectUrl(@Query("redirect") String redirect ,@Query("uid") String uid);

        /**
         *珊瑚积分商城免登录地址
         */
        @GET("api/integralMall/gMallUrl")
        Observable<JSONObject> gMallUrl(@Query("token") String token ,@Query("tenantId") String tenantId ,@Query("uid") String uid ,@Query("deviceId") String deviceId);


        /**
         * 对通过HTTPClient的请求精选转换封装4
         */
        @GET("{path}")
        Observable<JSONObject> getWrapper(@Path(value = "path", encoded = true) String path, @QueryMap Map<String, String> params);

        /**
         * 反恶意登录、注册
         * http://showdoc.chinamcloud.com/web/#/6?page_id=24312
         * @param body
         * @return
         */
        @POST("api/malicious/verifyToken")
        Observable<JSONObject> verifyToken(@Body RequestBody body);

        /**
         * 查询所有密保问题
         */
        @GET("api/answer/getAllTitle")
        Observable<JSONObject> getAllQuestion();

        /**
         * 根据会员手机号查询设置过的问题
         */
        @GET("api/answer/getTitleByMemberId")
        Observable<JSONObject> checkHasQuestion(@Query("mobile") String mobile);

        /**
         * 第一次设置密保问题
         */
        @POST("api/answer/setTitle")
        Observable<JSONObject> setAnswer(@Body RequestBody body);

        /**
         * 更新密保问题
         */
        @POST("api/answer/updateAnswerOrTitle")
        Observable<JSONObject> updateAnswer(@Body RequestBody body);

        /**
         * 验证密保问题
         */
        @POST("api/answer/verifyAnswer")
        Observable<JSONObject> verifyAnswer(@Body RequestBody body);


        /**
         * 获取登录校验二维码
         * memberId	是	long	会员ID
         * deviceId	是	string	设备ID
         * deviceName	是	string	设备名称
         * loginAddress	否	string	登录地址
         * @return
         */
        @GET("api/loginDeviceApply/getQRCode")
        Observable<JSONObject> getQRCode(@QueryMap Map<String, Object> params);
        /**
         * 获取老设备是否扫码授权
         * @param memberId 会员ID
         * @return
         */
        @GET("api/loginDeviceApply/getVerify")
        Observable<JSONObject> getScanVerifyStatus(@Query("memberId") String memberId);

        /**
         * 老设备扫码后授权通过
         * 老设备扫码后授权通过,请求此接口前，客户端需要先判断二维码中的memberId是否和当前登录用户一致
         * @param memberId 会员ID
         * @param status  是否通过：通过：2 不通过：3
         * @return
         */
        @FormUrlEncoded
        @POST("api/loginDeviceApply/passVerify")
        Observable<JSONObject> scanVerifyNewDevice(@Field("memberId") String memberId, @Field("status") Long status);


        /**
         * 短信验证码校验添加新设备
         * memberId	是	long	会员ID
         * deviceId	是	string	设备ID
         * deviceName	是	string	设备名称
         * loginAddress	否	string	登录地址
         * mobile	是	string	手机号码
         * @return
         */
        @FormUrlEncoded
        @POST("api/loginDeviceApply/sendMessage")
        Observable<JSONObject> sendSMSForSmsVerify(@FieldMap Map<String, Object> params);

        /**
         * 短信验证码校验
         * memberId	是	long	会员ID
         * verifyCode	是	string	短信验证码
         * mobile	是	string	电话号码
         * @return
         */
        @FormUrlEncoded
        @POST("api/loginDeviceApply/checkVerify")
        Observable<JSONObject> smsVerifyNewDeVice(@FieldMap Map<String, Object> params);



        /**
         * 人工申诉新设备登录
         * memberId	是	long	会员ID
         * deviceId	是	string	设备ID
         * deviceName	是	string	设备名称
         * loginAddress	否	string	登录地址
         * contactNumber	是	string	联系电话（必填，可与登录手机号不一致）
         * trueName	否	string	真实姓名
         * IdCard	否	string	身份证号
         * areaCode	否	string	地域名称
         * email	否	string	邮箱
         * remarks	否	string	备注
         * @return
         */
        @FormUrlEncoded
        @POST("api/loginDeviceApply/manualAppeal")
        Observable<JSONObject> appealNewDevice(@FieldMap Map<String, Object> params);


        @GET("api/rankLevel/getAllMemberRankLevel")
        Observable<JSONObject> getAllMemberRankLevel(@Query("tenantid") String tenantid,@Query("memberId") String memberId);

        /**
         * 用户人脸核身（腾讯云）
         */
        @GET("api/faceVerify/getSignAndTicket")
        Observable<JSONObject> getSignAndTicket(@Query("tenantId") String tenantId,@Query("memberId") String memberId,@Query("realName") String realName,@Query("idCard") String idCard);



        /**
         * 获取服务列表
         * @return
         */
        @GET("api/serviceManage/list")
        Observable<JSONObject> getServiceManageList(@QueryMap() Map<String, Object> params);

        /**
         * 获取服务分类接口
         * @return
         */
        @GET("api/serviceCategory/list")
        Observable<JSONObject> getServiceCategoryList();

        /**
         * 获取服务详情接口
         * @return
         */
        @GET("api/serviceManage/detail")
        Observable<JSONObject> getServiceDetail(@Query("id")int id);
        /**
         * 获取服务详情接口
         * @return
         */
        @GET("api/audit/occupationList")
        Observable<JSONObject> getOccupationList();

        @FormUrlEncoded
        @POST("api/audit/updateMemberInfo")
        Observable<JSONObject> updateMemberInfo(@Field("tenantId") String tenantId,@Field("memberId") Long memberId, @Field("newInfo") String newInfo, @Field("column") String column);


        /**
         * 用户行为统计更新接口
         * memberId	是	long	用户
         * field	是	string	viewCount
         * value	是	long		统计值
         * @return
         */
        @POST("api/action-statistics")
        Observable<JSONObject> statistics(@Body RequestBody body);


        @GET("api/audit/editLimit")
        Observable<JSONObject> getEditLimit(@Query("tenantid") String tenantid,@QueryMap() Map<String, String> params);

        //会员获取问卷一次性登录码
        @GET("api/questionnaire/getLoginCodeByOpenId")
        Observable<JSONObject> getLoginCodeByOpenId(@Query("memberId") String memberId);
    }
}
